<?php
namespace App\Models;

use App\Exceptions\ApiErrorException;
use App\Models\GoodsSpec;
use App\Util\ArrayUtil;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * 商品规格关系模型
 * Class GoodsSpecRel
 * @package app\common\model
 */
class GoodsRentSpecRel extends BaseModel
{


    const KEY = 'id';
    const TABLE = 'sp_goods_rent_spec_rel';

    protected $table = self::TABLE;
    protected $primaryKey = self::KEY;
    protected $connection = 'mysql';

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

    protected $guarded = [];

    protected $casts = [
        'create_time' => 'datetime:Y-m-d H:i:s',
        'update_time' => 'datetime:Y-m-d H:i:s',
    ];



    /**
     * 关联规格组
     * @return BelongsTo
     */
    public function spec()
    {
        return $this->belongsTo(GoodsRentSpec::class, 'spec_id', 'spec_id');
    }

    /**
     * 关联规格值
     * @return BelongsTo
     */
    public function specValue()
    {
        return $this->belongsTo(GoodsRentSpecValue::class,'spec_value_id', 'spec_value_id');
    }

    /**
     * 指定商品的规格列表
     * @param int $goodsId 商品ID
     * @return array
     */
    public static function getSpecList(int $goodsId): array
    {
        // 获取指定商品的规格值关系记录
        $data = static::getList($goodsId);
        // 规格组
        $groupData = [];
        foreach ($data as $groupKey => $item) {
            $groupData[$item['spec_id']] = [
                'spec_id' => $item['spec']['spec_id'],
                'spec_name' => $item['spec']['spec_name'],
                'is_image' => $item['spec']['is_image']
            ];
        }
        // 去除索引
        $specList = array_values($groupData);
        // 规格值
        foreach ($specList as $groupKey => &$group) {
            $group['key'] = $groupKey;
            foreach ($data as $valueKey => $item) {
                ($item['spec_id'] == $group['spec_id']) && $group['valueList'][] = [
                    'key' => isset($group['valueList']) ? count($group['valueList']) : 0,
                    'groupKey' => $groupKey,
                    'spec_value_id' => $item['specValue']['spec_value_id'],
                    'spec_value' => $item['specValue']['spec_value'],
                    'img_url' => $item['specValue']['img_url'],
                ];
            }
        }
        return $specList;
    }

    /**
     * 获取指定商品的规格值关系记录
     * @param int $goodsId 商品ID
     */
    private static function getList(int $goodsId)
    {
        return (new static)->with(['spec', 'specValue'])
            ->where('goods_id', '=', $goodsId)
            ->get();
    }

    public static function updates(int $goodsId, array $specList)
    {
        // 删除所有的记录
        static::query()->where('goods_id',$goodsId)->delete();
        // 批量新增记录
        return static::increased($goodsId, $specList);
    }
    /**
     * 批量写入商品与规格值关系记录
     * @param int $goodsId 商品ID
     * @param array $specList 规格数据
     * @return array|false
     */
    public static function increased(int $goodsId, array $specList)
    {
        $dataset = [];
        foreach ($specList as $item) {
            foreach ($item['valueList'] as $specValueItem) {
                $dataset[] = [
                    'goods_id' => $goodsId,
                    'spec_id' => $item['spec_id'],
                    'spec_value_id' => $specValueItem['spec_value_id'],
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s')
                ];
            }
        }
        return (new static)->insert($dataset);
    }
}
